import axios from 'axios';
import { Loading } from 'element-ui';

let loadingInstance;

const loadingOptions = {
    lock: true,
    text: '加载中...',
    // spinner: 'el-icon-loading',
    background: 'rgba(255, 255, 255, 0.7)'
}

const service = axios.create({
    // baseURL: 'http://134.98.104.102:8081/esbview',
    timeout: 5000
});

service.interceptors.request.use(
    config => {
        loadingInstance = Loading.service(loadingOptions);
        return config;
    },
    error => {
        loadingInstance.close();
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
        loadingInstance.close();
        if (response.status === 200) {
            // console.log(response.data);
            return response.data;
        } else {
            Promise.reject();
        }
    },
    error => {
        loadingInstance.close();
        console.log(error);
        return Promise.reject();
    }
);

/*网络请求部分*/

/*
 *  get请求
 *  url:请求地址
 *  params:参数
 * */
export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        service({
            url: url,
            method: 'get',
            params: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

/*
 *  post请求
 *  url:请求地址
 *  params:参数
 * */
export function post(url, params = {}) {
    return new Promise((resolve, reject) => {
        service({
            url: url,
            method: 'post',
            data: params,
            headers: {'Content-Type': 'application/json;charset=UTF-8'}
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

/*
 *  文件上传
 *  url:请求地址
 *  params:参数
 * */
export function fileUpload(url, params = {}) {
    return new Promise((resolve, reject) => {
        service({
            url: url,
            method: 'post',
            data: params,
            headers: {'Content-Type': 'multipart/form-data'}
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

export default {
    get,
    post,
    fileUpload
}
// export default service;
